import React, { useState } from "react";
import BulletinBoard from "../../components/BulletinBoard";
import "./index.less";
import { TAnnouncements } from "../../components/BulletinBoard/type";
import {
  addNotice,
  deleteNotice,
  getNotice,
  updateNotice,
} from "../../server/api";
import { Button, Form, Input, Modal, message } from "antd";
const AnnouncementManagement: React.FC = ({}) => {
  const [announcements, setAnnouncements] = useState<TAnnouncements[]>([]);
  const [open, setOpen] = useState(false);
  const [noticeId, setNoticeId] = useState(0);
  const [form] = Form.useForm();
  const handleChange = (current: number) => {
    setPagination({ ...pagination, current });
  };
  const [pagination, setPagination] = useState({
    total: 0,
    pageSize: 5,
    current: 1,
  });
  const getBBData = async () => {
    const res: any = await getNotice({
      pageNum: pagination.current,
      pageSize: pagination.pageSize,
    });
    setPagination({ ...pagination, total: res.total });
    setAnnouncements(res.records);
  };
  const handleCancel = () => {
    setOpen(false);
  };
  const handleOk = async () => {
    const values = await form.validateFields();
    if (noticeId) {
      await updateNotice({ ...values, id: noticeId });
      setNoticeId(0);
      form.resetFields();
      setOpen(false);
      message.success("修改成功");
    } else {
      await addNotice({ ...values });
      form.resetFields();
      setOpen(false);
      message.success("添加成功");
    }
    getBBData();
  };
  const addNotices = () => {
    setOpen(true);
  };
  const editorNotice = (id: number) => {
    setOpen(true);
    setNoticeId(id);
  };
  const deleteNotices = async (id: number) => {
    await deleteNotice({ id });
    message.success("删除成功");
    getBBData();
  };
  return (
    <div className="a-ctn">
      <Modal
        open={open}
        onCancel={handleCancel}
        onOk={handleOk}
        okText={"确定"}
        cancelText="取消"
      >
        <Form form={form} title={noticeId ? "编辑公告" : "添加公告"}>
          <Form.Item label="公告内容" name="content">
            <Input placeholder="请输入公告内容"></Input>
          </Form.Item>
          <Form.Item label="创建人" name="createUser">
            <Input placeholder="请输入创建人"></Input>
          </Form.Item>
        </Form>
      </Modal>
      <Button type="primary" onClick={addNotices}>
        新增公告
      </Button>
      <BulletinBoard
        editorNotice={editorNotice}
        deleteNotice={deleteNotices}
        announcements={announcements}
        handleChange={handleChange}
        pagination={pagination}
        getBBData={getBBData}
      />
    </div>
  );
};
export default AnnouncementManagement;
